import { Body, Controller, Get, Param, ParseIntPipe, Post, Query, Req } from '@nestjs/common';

import { PrivateDeviceService } from './private-device.service';
import { UtilsService } from '@app/utils';

@Controller('privateDevice')
export class PrivateDeviceController {
    constructor(
        private readonly service:PrivateDeviceService,
        private utils:UtilsService
    ){
    }

    @Get('charge/page')
    async page(@Query() query:Pagination&{deviceId:number}, @Req() { userId }) {
        let rows = await this.service.chargePage(query, query.deviceId)
        return this.utils.successRes(rows)
    }

    @Post('charging')
    async charging(@Body() body:{init?:number, id:number}) {
        const res = await this.service.charging(body.id, Number(body.init || 0))
        return this.utils.successRes(res)
    }

    @Get('charge/detail/:id')
    async detail(@Param('id', ParseIntPipe) id:number) {
        if(isNaN(id) || id < 1) return
        const res = await this.service.detail(id)
        return this.utils.successRes(res)
    }

    @Post('power/data')
    async powerData(@Body() dto:{id:number, pageNo:number, pageSize:number}) {
        const res = await this.service.powerData(dto.id, dto.pageNo, dto.pageSize)
        return this.utils.successRes(res ? res.data : null)
    }

    @Get('list')
    async list(@Req() { userId }){
        const devices = await this.service.list(userId)
        return this.utils.successRes(devices)
    }

    @Post('bind')
    async bindDevice(@Body('id', ParseIntPipe) id:number, @Req() { userId }){
        const r = await this.service.bind(userId, id)
        if(r === true) return this.utils.successRes()
        if(r == -1) {
            return this.utils.failRes('设备已被绑定')
        }
        return this.utils.failRes('绑定失败')
    }

    @Post('unbind')
    async unbindDevice(@Body('id', ParseIntPipe) id:number, @Req() { userId }){
        const r = await this.service.unbind(userId, id)
        if(r === true) return this.utils.successRes()
        return this.utils.failRes('解绑失败')
    }

    @Get('members/:id')
    async bindUser(@Param('id', ParseIntPipe) id:number){
        const users = await this.service.members(id)
        return this.utils.successRes(users)
    }

    @Post('bind/member')
    async bindMember(@Body('id', ParseIntPipe) id:number, @Body('phone') phone:string, @Req() { userId }){
        const r = await this.service.bindMember(userId, phone, id)
        if(r === null) return this.utils.failRes('无此用户')
        if(r === true) return this.utils.successRes()
        return this.utils.failRes('绑定失败')
    }

    @Post('unbind/member')
    async unbindMember(@Body('id', ParseIntPipe) id:number, @Body('user', ParseIntPipe) user:number, @Req() { userId }){
        const r = await this.service.unbindMember(userId, user, id)
        if(r === true) return this.utils.successRes()
        return this.utils.failRes('解绑失败')
    }
}
